<template>
<div>
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#4fc08d"
        @focus="isSuggestShow=false"
      />
    </form>

    <!-- 默认显示搜索历史
    当搜索框有内容的时候，显示联想建议
    当回车的时候，显示搜索结果 -->
    <!-- if(搜索框有内容){
      显示联想建议
    }else if(回车的时候){
      显示搜索结果
    }else{
      默认显示搜索历史
    } -->

    <!-- 历史记录 -->
    <search-result v-if="isSuggestShow" :search-text="value"  />
    <!-- /历史记录 -->

    <!-- 联想建议 -->
    <search-suggestion v-else-if="value" :searchText="value" @search-event="onSearch" />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history :searchHistories="searchHistories" v-else />
    <!-- /搜索历史记录 -->

</div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      value: '',
      isSuggestShow: false,
      searchHistories: []
    }
  },
  computed: {},
  watch: {
    // 不管是什么地方对这个数据进行了改变，这个watch都可以知道
    searchHistories: function () {
      setItem('TOUTIAO_HISTORY', this.searchHistories)
    }
  },
  created () {
    this.searchHistories = getItem('TOUTIAO_HISTORY') || []
  },
  mounted () {},
  methods: {
    onSearch (value) {
      // 先判断要加的是不是已经有了
      var index = this.searchHistories.indexOf(value)// -1
      if (index !== -1) this.searchHistories.splice(index, 1)
      this.searchHistories.unshift(value)
      console.log(this.searchHistories)
      this.value = value
      this.isSuggestShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped>

</style>
